package com.guangyuan.network.context;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.velocity.VelocityContext;

public class WebVelocityContext extends VelocityContext {

	private static final String REQUEST = "request";
	private static final String SESSION = "session";
	private static final String SERVLETCONTEXT = "servletContext";

	private ServletContext servletContext;
	private HttpServletRequest httpServletRequest;
	private HttpServletResponse httpServletResponse;
	private HttpSession httpSession;

	public WebVelocityContext(ServletContext servletContext,
			HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse, HttpSession httpSession) {
		this.servletContext = servletContext;
		this.httpServletRequest = httpServletRequest;
		this.httpServletResponse = httpServletResponse;
		this.httpSession = httpSession;
	}

	@Override
	public Object internalGet(String key) {
		System.out.println("test");
		if (REQUEST.equals(key)) {
			return httpServletRequest;
		}
		if (SESSION.equals(key)) {
			return httpSession;
		}
		if (SERVLETCONTEXT.equals(key)) {
			return servletContext;
		}

		Object obj = super.internalGet(key);

		if (null != obj) {
			return obj;
		}

		return getAttribute(key);
	}

	private Object getAttribute(String key) {
		Object obj = httpServletRequest.getAttribute(key);
		if (null == obj) {
			if (null != httpSession) {
				obj = httpSession.getAttribute(key);
			}

			if (null == obj) {
				obj = servletContext.getAttribute(key);
			}
		}

		return obj;
	}

	public ServletContext getServletContext() {
		return servletContext;
	}

	public HttpServletRequest getHttpServletRequest() {
		return httpServletRequest;
	}

	public HttpServletResponse getHttpServletResponse() {
		return httpServletResponse;
	}

	public HttpSession getHttpSession() {
		return httpSession;
	}

}
